#include "datashow.h"
#include "ui_datashow.h"
#include "globalval.h"

DataShow::DataShow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DataShow)
{
    ui->setupUi(this);
    // 添加key值和label的映射
    dataMap.insert(101,ui->peopleNum);
    dataMap.insert(103,ui->windPressure);
    dataMap.insert(301,ui->humb);
    dataMap.insert(302,ui->temp);
    dataMap.insert(102,ui->Concentration);

    h = new History(this);
    // 给labelimg添加点击事件
    ui->labelPeople_img->installEventFilter(this);
    ui->labelWind_img->installEventFilter(this);
    ui->labelHumb_img->installEventFilter(this);
    ui->label5Temp_img->installEventFilter(this);
    ui->labelCon_img->installEventFilter(this);

}

DataShow::~DataShow()
{
    delete ui;
}
// label点击事件函数
bool DataShow::eventFilter(QObject *watched, QEvent *event) {
    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::LeftButton) {
            QLabel *label = qobject_cast<QLabel *>(watched); // 获取点击的label
            if (label) {
                QString title;
                int key;
                // 设置给历史记录界面的参数
                if (label == ui->labelPeople_img) {
                    title = "车间人数";
                    key = 101;
                } else if (label == ui->labelWind_img) {
                    title = "风压";
                    key = 103;
                } else if (label == ui->labelHumb_img) {
                    title = "湿度";
                    key = 301;
                } else if (label == ui->label5Temp_img) {
                    title = "温度";
                    key = 302;
                } else if (label == ui->labelCon_img) {
                    title = "粉尘浓度";
                    key = 102;
                }

                h->setTitle(title);
                h->setKey(key);
                h->show();
                QObject::connect(GlobalVal::mqtt, SIGNAL(dataUpSignal(QByteArray)),
                                 h, SLOT(dataUpSlot(QByteArray)));
                return true;
            }
        }
    }
    return QDialog::eventFilter(watched, event);
}
// 获取mqtt的数据渲染到页面上
void DataShow::dataShowToUi(QJsonObject jsonData)
{
    if (jsonData.contains("data") && jsonData["data"].isArray()) {
        QJsonArray dataArray = jsonData["data"].toArray();
        for (const QJsonValue &value : dataArray) {
            if (value.isObject()) {
                QJsonObject obj = value.toObject();
                int key = obj["key"].toInt();
                QString val = obj["val"].toString();
                int type = obj["type"].toInt();
                if(dataMap.contains(key))
                {
                    dataMap[key]->setText(val);
                }

            } else {
                qDebug() << "Unexpected value type in data array";
            }
        }
    } else {
        qDebug() << "No 'data' array found in the JSON object";
    }
}
